/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.logistics.web.ladingbill;

import com.alibaba.fastjson.JSONValidator;
import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.base.entity.cars.Tcar;
import com.jeesite.modules.base.entity.customer.Customer;
import com.jeesite.modules.base.entity.fixedexpense.VehicleSettlementInfo;
import com.jeesite.modules.base.entity.supplier.Supplier;
import com.jeesite.modules.base.service.cars.TcarService;
import com.jeesite.modules.base.service.customer.CustomerService;
import com.jeesite.modules.base.service.supplier.SupplierService;
import com.jeesite.modules.custom.enumInfo.logisticsStatusEnum;
import com.jeesite.modules.custom.enumInfo.payMethodEnum;
import com.jeesite.modules.custom.enumInfo.warehourseEnum;
import com.jeesite.modules.financial.entity.arrivalreminder.ArrivalReminder;
import com.jeesite.modules.financial.service.arrivalreminder.ArrivalReminderService;
import com.jeesite.modules.logistics.entity.ladingbill.LadingBill;
import com.jeesite.modules.logistics.entity.ladingbill.LadingBillDetail;
import com.jeesite.modules.logistics.service.ladingbill.LadingBillService;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrderDetail;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.service.EmpUserService;
import com.mchange.v1.util.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.beetl.ext.fn.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 提单Controller
 *
 * @author LV
 * @version 2021-03-09
 */
@Controller
@RequestMapping(value = "${adminPath}/logistics/ladingbill/ladingBill")
public class LadingBillController extends BaseController {

    @Autowired
    private LadingBillService ladingBillService;
    @Autowired
    private ServiceOrderService serviceOrderService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private ArrivalReminderService arrivalReminderService;
    @Autowired
    private TcarService carService;
    @Autowired
    private EmpUserService empUserService;


    /**
     * 获取数据
     */
    @ModelAttribute
    public LadingBill get(String ladingBillId, boolean isNewRecord) {
        return ladingBillService.get(ladingBillId, isNewRecord);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("logistics:ladingbill:ladingBill:view")
    @RequestMapping(value = {"list", ""})
    public String list(LadingBill ladingBill, Model model) {
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listCustomer", customerService.findList(new Customer()));
        model.addAttribute("listUser", empUserService.findList(new EmpUser()));
        model.addAttribute("ladingBill", ladingBill);
        return "modules/logistics/ladingbill/ladingBillList";
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("logistics:ladingbill:ladingBill:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page < LadingBill > listData(LadingBill ladingBill, HttpServletRequest request, HttpServletResponse response) {
        ladingBill.setPage(new Page <>(request, response));
        Page < LadingBill > page = ladingBillService.findPage(ladingBill);
        return page;
    }

    /**
     * 查看编辑表单
     */
    @RequiresPermissions("logistics:ladingbill:ladingBill:view")
    @RequestMapping(value = "form")
    public String form(LadingBill ladingBill, Model model) {
        model.addAttribute("listArrivalReminder", arrivalReminderService.findList(new ArrivalReminder()));// 到单提醒
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listCustomer", customerService.findList(new Customer()));
        model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
        Supplier supplier = new Supplier();
        supplier.setSupplierType(warehourseEnum.YUNSHUGONGSI.getCode());
        model.addAttribute("listTransportSupplier", supplierService.findList(supplier));
        model.addAttribute("listCar", carService.findList(new Tcar()));
        model.addAttribute("ladingBill", ladingBill);
        return "modules/logistics/ladingbill/ladingBillForm";
    }

    /**
     * 查看表单详情
     */
    @RequiresPermissions("logistics:ladingbill:ladingBill:view")
    @RequestMapping(value = "detail")
    public String detail(LadingBill ladingBill, Model model) {
        model.addAttribute("listArrivalReminder", arrivalReminderService.findList(new ArrivalReminder()));// 到单提醒
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listCustomer", customerService.findList(new Customer()));
        model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
        Supplier supplier = new Supplier();
        supplier.setSupplierType(warehourseEnum.YUNSHUGONGSI.getCode());
        model.addAttribute("listTransportSupplier", supplierService.findList(supplier));
        model.addAttribute("listCar", carService.findList(new Tcar()));
        model.addAttribute("ladingBill", ladingBill);
        return "modules/logistics/ladingbill/ladingBillDetail";
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("logistics:ladingbill:ladingBill:edit")
    @PostMapping(value = "save")
    @ResponseBody
    public String save(@Validated LadingBill ladingBill) {
        /**
         * 车间耗校验重复
         * 1、已经删除的行信息的车架号
         * 2、新增或修改的行信息的车架号
         * 3、搜出除除订单行之外的车架号信息--去重后，将新增和删除的车架号信息增加到其中，判断是否重复
         * 4、付款方式为TT的 不进行校验
         */
        if (!payMethodEnum.TT.getCode().equals(ladingBill.getPaymentMethod())){
            List<String> newFameNumbers = ListUtils.newArrayList();
            List<String> deleteFameNumbers = ListUtils.newArrayList();
            for (LadingBillDetail ladingBillDetail : ladingBill.getLadingBillDetailList()) {
                if (!LadingBillDetail.STATUS_DELETE.equals(ladingBillDetail.getStatus())){
                    if (StringUtils.isNoneEmpty(ladingBillDetail.getFrameNumber())){
                        newFameNumbers.add(ladingBillDetail.getFrameNumber());
                    }
                }else{
                    if (StringUtils.isNoneEmpty(ladingBillDetail.getFrameNumber())){
                        deleteFameNumbers.add(ladingBillDetail.getFrameNumber());
                    }
                }
            }
            List<String> frameNumberByRemove = serviceOrderService.getFrameNumberByRemove(deleteFameNumbers);
            frameNumberByRemove.addAll(newFameNumbers);
            Integer newFrameNumberCount = frameNumberByRemove.size();
            List<String> list1 = frameNumberByRemove.stream().distinct().collect(Collectors.toList());
            if (newFrameNumberCount != list1.size()){
                return renderResult(Global.FALSE, text("存在相同的车架号！"));
            }
        }

        ladingBillService.save(ladingBill);
        /*try {
        } catch (Exception e) {
            return renderResult(Global.FALSE, text("操作存在异常，请联系管理员！"));
        }*/
        return renderResult(Global.TRUE, text("保存提单成功！"));
    }

    /**
     * 删除数据
     */
    @RequiresPermissions("logistics:ladingbill:ladingBill:delete")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(LadingBill ladingBill) {
        ladingBillService.delete(ladingBill);
        return renderResult(Global.TRUE, text("删除提单成功！"));
    }

    /**
     * 列表选择对话框
     */
    @RequiresPermissions("logistics:ladingbill:ladingBill:view")
    @RequestMapping(value = "ladingBillSelect")
    public String empUserSelect(LadingBill ladingBill, String selectData, Model model) {
        String selectDataJson = EncodeUtils.decodeUrl(selectData);
        if (selectDataJson != null && JSONValidator.from(selectDataJson).validate()) {
            model.addAttribute("selectData", selectDataJson);
        }
        model.addAttribute("LadingBill", ladingBill);
        return "modules/logistics/ladingbill/ladingBillSelect";
    }


    @RequiresPermissions("logistics:ladingbill:ladingBill:view")
    @RequestMapping(value = "createFromArrival")
    public String createFromArrival(ArrivalReminder arrivalReminder, Model model) {
        LadingBill ladingBill = new LadingBill();
        if (StringUtils.isNotEmpty(arrivalReminder.getServiceOrderId())) {
            ServiceOrder oldServiceOrder = serviceOrderService.get(arrivalReminder.getServiceOrderId());
            // 服务订单
            ladingBill.setServiceOrderId(arrivalReminder.getServiceOrderId());
            // 到单提醒
            ladingBill.setArrivalReminderCode(arrivalReminder.getArrivalReminderId());
            // 国内资方
            ladingBill.setInvestorId(oldServiceOrder.getInvestorId());
            // 客户名称
            ladingBill.setCustomerId(oldServiceOrder.getCustomer().getCustomerId());
            // 供货外商
            ladingBill.setSupplierId(oldServiceOrder.getSupplierId());
            // 外商名称
            ladingBill.setForeignBusinessmenId(oldServiceOrder.getForeignBusinessmenId());
            // 付款方式
            ladingBill.setPaymentMethod(oldServiceOrder.getPaymentMethod());
            // 起运港
            ladingBill.setFromPort(oldServiceOrder.getFromPort());
            // 目的港
            ladingBill.setToPort(oldServiceOrder.getToPort());
            // 车辆信息
            List < LadingBillDetail > ladingBillDetailList = ListUtils.newArrayList();
            List < ServiceOrderDetail > serviceOrderDetailList = oldServiceOrder.getServiceOrderDetailList();
            for (ServiceOrderDetail SODetail : serviceOrderDetailList) {
                // 提单ID 等于空
                if (StringUtils.isEmpty(SODetail.getLadingBillId())) {
                    LadingBillDetail ladingBillDetail = new LadingBillDetail();
                    ladingBillDetail.setRowNumber(SODetail.getRowNumber());
                    ladingBillDetail.setCarId(SODetail.getCarId());
                    ladingBillDetail.setTcar(SODetail.getTcar());
                    ladingBillDetail.setModel(SODetail.getModel());
                    ladingBillDetail.setPrice(SODetail.getUnitPrice());
                    ladingBillDetail.setFrameNumber(SODetail.getFrameNumber());
                    ladingBillDetail.setDetailStatus(logisticsStatusEnum.CAR_ARRIVALPORT.getCode());
                    ladingBillDetail.setEngineNumber(SODetail.getEngineNumber());
                    ladingBillDetail.setProductionDate(SODetail.getProductionDate());
                    ladingBillDetail.setFactory(SODetail.getFactory());
                    ladingBillDetail.setTireSize(SODetail.getTireSize());
                    ladingBillDetail.setSeatNumber(SODetail.getSeatNumber());
                    ladingBillDetailList.add(ladingBillDetail);
                }
            }
            ladingBill.setLadingBillDetailList(ladingBillDetailList);

            model.addAttribute("listArrivalReminder", arrivalReminderService.findList(new ArrivalReminder()));// 到单提醒
            model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
            model.addAttribute("listCustomer", customerService.findList(new Customer()));
            model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
            Supplier supplier = new Supplier();
            supplier.setSupplierType(warehourseEnum.YUNSHUGONGSI.getCode());
            model.addAttribute("listTransportSupplier", supplierService.findList(supplier));
            model.addAttribute("listCar", carService.findList(new Tcar()));
            model.addAttribute("ladingBill", ladingBill);
            return "modules/logistics/ladingbill/ladingBillForm";
        } else {
            return renderResult(Global.FALSE, text("未查找到服务订单的相关信息！"));
        }
    }


}